package com.starry.push.netty.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.starry.push.netty.domain.LogPushTask;
import com.starry.push.netty.domain.LogWsConnect;
import com.starry.push.netty.vo.*;
import com.starry.push.netty.websocket.WebSocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/11/9 15:50
 */
@Service
public class PushServiceImpl implements PushService {
    @Autowired
    private LogWsConnectService logWsConnectService;
    @Autowired
    private LogPushTaskService logPushTaskService;


    @Override
    public HttpEntity commonPush(String channelId, String uniqueIdentification, Object msg) {
        if (StringUtils.isBlank(channelId) && StringUtils.isBlank(uniqueIdentification)) {
            return ResponseEntity.ok(ResponseResult.error("推送id和唯一标识不能同时为空"));
        }
        if (StringUtils.isNotBlank(channelId)) {
            List<LogWsConnect> connects = logWsConnectService.list(new QueryWrapper<LogWsConnect>()
                    .eq(LogWsConnect.COL_CHANNEL_ID, channelId)
                    .eq(LogWsConnect.COL_STATUS, 1)
            );
            if (CollectionUtils.isNotEmpty(connects)) {
                connects.forEach(logWsConnect -> {
                    String idStr = IdWorker.getIdStr();

                    WsResponse response = WsResponse.success(idStr, "正常", msg);
                    Channel channel = WebSocketHandler.onlineGroup.get(logWsConnect.getChannelId());
                    if (channel != null) {
                        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
                        logPushTaskService.save(
                                LogPushTask.builder().channelId(channel.id().asLongText())
                                        .pushId(idStr)
                                        .status(1)
                                        .createTime(LocalDateTime.now())
                                        .channelId(channelId)
                                        .content(JSONObject.toJSONString(msg))
                                        .build());
                    }
                });
                return ResponseEntity.ok(ResponseResult.success("推送成功"));
            } else {
                return ResponseEntity.ok(ResponseResult.error("无有效链接"));
            }
        }
        if (StringUtils.isNotBlank(uniqueIdentification)) {
            List<LogWsConnect> connects = logWsConnectService.list(new QueryWrapper<LogWsConnect>()
                    .eq(LogWsConnect.COL_UNIQUE_IDENTIFICATION, uniqueIdentification)
                    .eq(LogWsConnect.COL_STATUS, 1)
            );
            if (CollectionUtils.isNotEmpty(connects)) {
                connects.forEach(logWsConnect -> {
                    String idStr = IdWorker.getIdStr();
                    WsResponse response = WsResponse.success(idStr, "正常", msg);
                    Channel channel = WebSocketHandler.onlineGroup.get(logWsConnect.getChannelId());
                    if (channel != null) {
                        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
                        logPushTaskService.save(
                                LogPushTask.builder().channelId(channel.id().asLongText())
                                        .pushId(idStr)
                                        .status(1)
                                        .createTime(LocalDateTime.now())
                                        .channelId(channelId)
                                        .uniqueIdentification(uniqueIdentification)
                                        .content(JSONObject.toJSONString(msg))
                                        .build());
                    }
                });
                return ResponseEntity.ok(ResponseResult.success("推送成功"));
            } else {
                return ResponseEntity.ok(ResponseResult.error("无有效链接"));
            }
        }
        return ResponseEntity.ok(ResponseResult.error("无有效链接"));
    }

    @Override
    public HttpEntity PushAll(String msg) {
        String idStr = IdWorker.getIdStr();
        WsResponse response = WsResponse.success(idStr, "正常", msg);
        WebSocketHandler.channelGroup.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
        return ResponseEntity.ok(ResponseResult.success());
    }
}